const Mock = require('mockjs')
const { list: listRooms, find: findRoom } = require('./rooms')
const { find: findOrgUnit } = require('./org-units')
const {find: findMovie} = require('./movie')

let MovieTests = []

const roomsPage = listRooms(1, 150)
const movieNames = ['一点半', '山上有鬼']
let id = 1
for (let i = 0; i < roomsPage.data.records.length; ++i) {
  const orgUnit = findOrgUnit(roomsPage.data.records[i].orgUnitId)
  for (let j = 0; j < movieNames.length; ++j) {
    MovieTests.push(Mock.mock({
      id: id++,
      movieName: movieNames[j],
      orgUnitName: orgUnit.name,
      orgUnitId: roomsPage.data.records[i].orgUnitId,
      roomId: roomsPage.data.records[i].id,
      roomName: roomsPage.data.records[i].name
    }))
  }
}

function add(item) {
  const r = JSON.parse(JSON.stringify(item))
  r.id = MovieTests[MovieTests.length - 1].id + 1
  const room = findRoom(r.roomId)
  if (room) {
    r.roomName = room.name
    r.orgUnitName = room.orgUnitName
  }
  const movie = findMovie(r.movieId)
  if (movie) {
    r.movieName = movie.name
  }
  MovieTests.push(r)
}

function list(page, limit, movieId, orgUnitId, roomId) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  roomId = roomId ? parseInt(roomId) : null
  movieId = movieId ? parseInt(movieId) : null

  let mocks = MovieTests.filter(item => {
    if (movieId && item.movieId !== movieId) return false
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    return !(roomId && item.roomId !== orgUnitId)
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  return { success: true, data: { total: total, records: mocks }}
}

function deleteRecord(id) {
  id = id ? parseInt(id) : null
  if (id) {
    MovieTests = MovieTests.filter(item => item.id !== id)
  }
}

module.exports = { list, add, deleteRecord }
